﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace LunarStudentInfosReader
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnLoadDatabase_Click(object sender, RoutedEventArgs e)
        {
            LoadView(dataGrid, "select * from StudentInfos");
        }

        public void LoadView(ItemsControl control, string commandText)
        {
            try
            {
                OpenFileDialog ofd = new OpenFileDialog() { Filter = "Sqlite3数据库（*.db）|*.db", };
                if (ofd.ShowDialog() != true) return;

                var dbFilePath = ofd.FileName;

                using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + dbFilePath + ";UserId=Admin;Password=DyBj#PpBb;"))
                {
                    connection.Open();
                    using (SQLiteCommand command = new SQLiteCommand(commandText, connection))
                    {
                        using (SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(command))
                        {
                            DataTable dataTable = new DataTable();
                            dataAdapter.Fill(dataTable);
                            control.ItemsSource = dataTable.AsDataView();
                            tbRecordsCount.Text = $"当前共有 {dataTable.Rows.Count} 条记录！";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnCopyData_Click(object sender, RoutedEventArgs e)
        {
            dataGrid.SelectionMode = DataGridSelectionMode.Extended;
            dataGrid.SelectAll();
            dataGrid.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
            ApplicationCommands.Copy.Execute(null, dataGrid);
            dataGrid.SelectionMode = DataGridSelectionMode.Single;
            MessageBox.Show("已复制到剪贴板！");
        }
    }
}
